package com.lez.flowpractice2.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.lez.flowpractice2.adapter.UserAdapter
import com.lez.flowpractice2.databinding.FragmentUserBinding
import com.lez.flowpractice2.viewmodel.UserViewModel
import kotlinx.coroutines.flow.collect

class UserFragment : Fragment() {

    private val mBinding: FragmentUserBinding by lazy {
        FragmentUserBinding.inflate(layoutInflater)
    }
    //拿到UserViewModel
    private val userViewModel by viewModels<UserViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return mBinding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mBinding.apply {
            addUser.setOnClickListener{
               userViewModel.insert(userID.text.toString(),firstName.text.toString(),lastName.text.toString())
            }
        }
        context?.let {
            val adapter = UserAdapter(it)
            mBinding.recyclerView.adapter = adapter
            mBinding.recyclerView.layoutManager = LinearLayoutManager(context)
            lifecycleScope.launchWhenCreated {
                userViewModel.getAll().collect { value->
                    adapter.setData(value)
                }
            }
        }
    }

}